#!/bin/bash
# 生产环境部署脚本

set -e

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

echo "脚本目录: $SCRIPT_DIR"
echo "项目目录: $PROJECT_DIR"
echo ""

cd "$PROJECT_DIR"

echo "============================================"
echo "SkyWalking 数据采集系统 - 生产环境部署"
echo "============================================"
echo ""

# 检查 Docker 和 Docker Compose
if ! command -v docker &> /dev/null; then
    echo "❌ 错误: 找不到 docker 命令"
    echo "请先安装 Docker: https://docs.docker.com/engine/install/"
    exit 1
fi

if ! docker compose version &> /dev/null; then
    echo "❌ 错误: 找不到 docker compose 命令"
    echo "请升级 Docker 到最新版本"
    exit 1
fi

# 检查配置文件
if [ ! -f "config.prod.env" ]; then
    echo "⚠️  警告: config.prod.env 不存在，从模板复制..."
    cp config.env config.prod.env
    echo "请编辑 config.prod.env 并重新运行此脚本"
    exit 1
fi

# 显示配置信息
echo "📋 配置信息:"
echo "  - SkyWalking: $(grep SKYWALKING_URL config.prod.env | cut -d'=' -f2)"
echo "  - 数据库: PostgreSQL 15"
echo "  - 采集间隔: $(grep COLLECTION_INTERVAL config.prod.env | cut -d'=' -f2) 分钟"
echo "  - Dashboard 端口: 8501"
echo ""

# 询问是否继续
read -p "是否继续部署? (y/n) " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "取消部署"
    exit 0
fi

echo ""
echo "🚀 开始部署..."
echo ""

# 停止并清理旧容器
echo "🧹 清理旧容器和网络..."
docker rm -f skywalking-postgres skywalking-collector skywalking-dashboard 2>/dev/null || true
docker network rm docker_skywalking-network 2>/dev/null || true
docker compose -f docker/docker-compose.prod.yml down 2>/dev/null || true

echo "✅ 清理完成"

# 构建镜像
echo ""
echo "📦 构建 Docker 镜像..."
docker compose -f docker/docker-compose.prod.yml build

# 启动服务
echo ""
echo "🚀 启动服务..."
docker compose -f docker/docker-compose.prod.yml up -d

# 等待服务启动
echo ""
echo "⏳ 等待服务启动..."
sleep 10

# 检查服务状态
echo ""
echo "📊 服务状态:"
docker compose -f docker/docker-compose.prod.yml ps

echo ""
echo "============================================"
echo "✅ 部署完成！"
echo "============================================"
echo ""
echo "📝 服务信息:"
echo "  - PostgreSQL: localhost:5432"
echo "    - 数据库: skywalking"
echo "    - 用户名: skywalking"
echo "    - 密码: skywalking@2024"
echo ""
echo "  - Dashboard: http://10.10.50.46:8501"
echo ""
echo "🔍 查看日志:"
echo "  - 采集服务: docker logs -f skywalking-collector"
echo "  - Dashboard: docker logs -f skywalking-dashboard"
echo "  - PostgreSQL: docker logs -f skywalking-postgres"
echo ""
echo "🛑 停止服务:"
echo "  cd $PROJECT_DIR && docker compose -f docker/docker-compose.prod.yml down"
echo ""
echo "📦 备份数据库:"
echo "  docker exec skywalking-postgres pg_dump -U skywalking skywalking > backup.sql"
echo ""

